<?php
require_once getcwd() . '/service.impl/UserManager.php';
require_once getcwd() . '/models/User.php';

	class InitController extends MyController {
		
		private $manager;
		
		public function __construct(){
			$this->manager = new UserManager();
		}
		
		
		public function getAction($request){
			$data = array();			
			if(isset($request->url_elements[2]) and count($request->url_elements) == 3){
				$data["messaage"] = "Success";
				$data['code'] = 200;
			}
			else {
				//redirection 500
				$data['code'] = 500;
				$data["messaage"] = "Internal Error";
			}
			return $data;
		}
		
		public function postAction($request){
			$data = array();
			$vardate = date("d/m/Y-H:i:s");			
			error_log($vardate ." - InitPostAction : \n" , 3, "log/mes-erreurs.log");
			error_log($vardate ."InitPost Action : ".$_POST['deviceId']. "\n",3,"log/mes-erreurs.log");
			if(isset($request->url_elements[2]) and count($request->url_elements) == 3){
				if(isset($_POST['deviceId']) and !empty($_POST['deviceId'])){
					$deviceId = $_POST['deviceId'];
					$vari = $deviceId;
					
					error_log($vardate ." - InitController: initialisation utilisateur ". $vari." \n" , 3, "log/mes-erreurs.log");
					$user = new User($deviceId);
					$manager = $this->manager;
					$result = $manager->insert($user);
					
					if($result==1){
						
						$data["message"] ="Success";
						$data['code'] = 201;
					}
					else {
						if($result== -1){
							$data["message"] = "User already exists";
							$data["code"] = 200;
									
						}
						else {
							$data["message"] = "Saving user failed";
							$data['code'] = 500;
						}
					}
					
					
					
				}else{
					$data['code'] = 400;
					$data["message"] = "Bad request : unknown parameters";
				}
				
			}
			else {
				$data['code'] = 400;
				$data["message"] = "Unknow request";
			}
			
			return $data;
			
		}
		
	}
?>